﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Microsoft.AspNet.SignalR;
using SignalRDemo.Common.Helpers;

namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }

        /// <summary>
        /// 供客户端调用的服务器端代码
        /// </summary>
        /// <param name="fsd">消息接收方</param>
        /// <param name="message"></param>
        public void Send(string fsd, string message)
        {
            var name = Guid.NewGuid().ToString().ToUpper();

            //var connectionId = this.Context.ConnectionId;
            //Clients.Client(connectionId).sendMessage(name, message);//发送给指定的客户端
            //var id = Clients.Connection.Identity;

            //GlobalHost.DependencyResolver.Register(typeof(IConnectionIdPrefixGenerator), () => new CustomConnectionIdPrefixGenerator());

            var connectIds = SignalRHelper.GetUserConnectionIds(fsd);
            if (connectIds.Any())
                Clients.Clients(connectIds).sendMessage(fsd, message);
            else
                // 调用所有客户端的sendMessage方法
                Clients.All.sendMessage(fsd, message);
        }

        /// <summary>
        /// 客户端连接的时候调用
        /// </summary>
        public override Task OnConnected()
        {
            Trace.WriteLine("客户端连接成功");
            return base.OnConnected();
        }


        public bool Addtoken(string token)
        {
            SignalRHelper.AddConnectionId(token, Context.ConnectionId);

            return true;
        }
    }
}